package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeign;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {
    @Value("${jobCron.seckillCache}")
    private String cron;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SeckillProductFeign seckillProductFegin;

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println(shardingContext.getShardingParameter());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String time) {
        //远程调用秒杀服务查询数据 List<SeckillProductVo>
        Result<List<SeckillProductVo>> result = seckillProductFegin.findByTime(Integer.parseInt(time));
        //result三种情况
        /**
         * 1.如果服务器挂掉了，走降级服务，返回值为null
         * 2.如果调用服务抛异常了，被统一异常处理到 {code:50201,msg:xxxx}
         * 3.正常返回   {cde:200,msg:"操作成功",data:List<SeckillProductVo>}
         */
    if (result!=null && !result.hasError()){
        //进来说明是正常返回
        //先拿出result中的vo数据
        List<SeckillProductVo> vos = result.getData();
        //将数据放入redis中
        //redis结构设计 key：SeckillProductList:time value:  key:seckillId    value:单个的SeckillProductVo
        for (SeckillProductVo vo : vos) {
            //把秒杀商品放入Redis中
            redisTemplate.opsForHash().
                    put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),
                        vo.getId() + "",
                        JSON.toJSONString(vo));

            //把库存放到Redis中
            redisTemplate.opsForHash()
                    .put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),
                         vo.getId() + "",
                         vo.getStockCount() + "");
        }
    }
    }
}
